package com.stylefeng.guns.modular.pay.controller.api;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.stylefeng.guns.GunsApplication;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.HttpClient;
import com.stylefeng.guns.core.util.HttpResp;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.core.util.ObjectUtils;
import com.stylefeng.guns.modular.pay.model.MchInfo;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.payment.jft.api.ApiNotifyRsponse;
import com.stylefeng.guns.modular.pay.payment.jft.common.JftConfigure;
import com.stylefeng.guns.modular.pay.payment.jft.core.AESUtil;
import com.stylefeng.guns.modular.pay.service.IJftPayService;
import com.stylefeng.guns.modular.pay.service.IMchInfoService;
import com.stylefeng.guns.modular.pay.service.INotifyRecordService;
import com.stylefeng.guns.modular.pay.service.ITransService;

/**
 *  佳付通
 * @author DevinYang
 * @date 2018年7月23日  
 *
 */
@Controller
@RequestMapping("/gateway/jft/")
public class ApiPayController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);

	private ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private IJftPayService jftPayService;
	@Autowired
	private ITransService transService;
	@Autowired
	private IMchInfoService mchInfoService;
	@Autowired
	private INotifyRecordService notifyRecordService;
	
	
	//快捷支付
	@ResponseBody
	@RequestMapping(value = "/quick")
	public Object wapPay(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.quickPay(params);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/memberReg")
	public Object memberReg(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.memberReg(params);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/memberBus")
	public Object memberBus(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.memberBus(params);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/rateModify")
	public Object rateModify(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.rateModify(params);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/bankCardModify")
	public Object bankCardModify(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.bankCardModify(params);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/query")
	public Object query(HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws Exception {
		Map<String, String> params = getRequestParams(httpRequest);
		logger.info("支付请求参数：" + mapper.writeValueAsString(params));
		Object obj =  jftPayService.query(params);
		return obj;
	}
	
	
	
	@RequestMapping("/notify")
	public void alipayNotify(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			String encryptData = request.getParameter("encryptData");
			logger.info("佳付通异步回写：" + mapper.writeValueAsString(encryptData));
			JSONObject resObject = null; 
			try {
				byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
				resObject = JSON.parseObject(new String(resDate,"UTF-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.info("解码后：" +resObject.toString());
			if("0000".equals(resObject.get("resCode"))){
				String orderCode = resObject.getString("orderCode");
				Trans trans = transService.findByPlatOrderCode(orderCode);
				ApiNotifyRsponse res = jftPayService.notify(resObject,trans);
				if (!Strings.isNullOrEmpty(trans.getCallBackUrl())) {
					MchInfo mch = mchInfoService.findByMchNo(trans.getMchNo());
					logger.info("jft异步信息转发第三方：" + mapper.writeValueAsString(res));
					Map<String, String> map = MD5Utils.signMap(ObjectUtils.Obj2Map(res), "MD5", mch.getMd5Key(), "UTF-8");
					HttpResp notifyRes  = HttpClient.doPost2(trans.getCallBackUrl(),map, "UTF-8", 1800, 1800);					
					logger.info(orderCode + "响应编码：" + notifyRes.getStatus());
					//通知日志
					notifyRecordService.notifyLog(trans,MD5Utils.createLinkString(map),notifyRes);
					writer.write("0000");
					writer.flush();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			writer.write("fail");
			writer.flush();
			writer.close();
		}
	}
}
